package com.znyj.cloud.chain.util;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpResponse;

import java.util.List;

/**
 * Created by gaoliwei on 15-2-26.
 */
public class ControllerUtil {
    /**
     * 当发生验证失败，字段缺失等情况
     *
     * @param json
     * @param ctx
     */
    public static String failResponse(JSONObject json, ChannelHandlerContext ctx) {
        FullHttpResponse response = HttpUtil.getDefaultJsonFailResponse(json);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        return json.toString();
//        if (errorMsg != null) {
//            return "{\"code\":1,\"message\":\"" + errorMsg + "\",\"data\":{\"bytesList\":[]}}";
//        } else {
//            return "{\"code\":1,\"message\":\"fail\",\"data\":{\"bytesList\":[]}}";
//        }
    }

    public static String defaultSuccessResponse(JSONObject json, ChannelHandlerContext ctx) {
        FullHttpResponse response = HttpUtil.getDefaultJsonSuccessResponse(json);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        return json.toString();
    }

//    public static String successResponse(List<ByteBuf> backBuffers, ChannelHandlerContext ctx) {
//
//        if (null == backBuffers || backBuffers.size() == 0) {
//            String response = ControllerUtil.defaultSuccessResponse(ctx);
//            return response.toString();
//        }
//
//        //将返回的buffer包装并发回请求者
//        List<String> hexStrings = ByteUtil.assembleBytes2HexStr(backBuffers);
//
//        //此时释放返回的buffers
//        ByteUtil.releaseBuffers(backBuffers);
//
//        String content = HttpUtil.getResult(hexStrings).toString();
//        FullHttpResponse response = HttpUtil.getJsonResponse(content);
//
//        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
//
//        return content;
//    }
}
